// https://mock.apipark.cn/m1/4727741-4380238-default
axios.defaults.baseURL = 'https://mock.apipark.cn/m1/4727741-4380238-default';


//封装轻提示函数
function showToast(msg) {
  const toastDom = document.querySelector('.my-toast');
//实例化toast组件
  const toast = new bootstrap.Toast(toastDom);
  //修改提示
  document.querySelector('.toast-body').innerText = msg;
  //显示提示
  toast.show();
}

//显示用户名
function renderUsername() {
    const username = localStorage.getItem('username');
    document.querySelector('.username').innerHTML = username
}

//非法调验
function checkLogin() {
    //判断token是否存在
    const token = localStorage.getItem('token');
    
    //如果token不存在，跳转到登录页面
    if (token == null) {
        showToast('请先登录');
        setTimeout(() => {
            window.location.href = '/login.html';
        },1500)  
    }
}

//退出登录
function registerLogout() {
    document.querySelector('#logout').addEventListener('click', () => {
        //清除token
        localStorage.removeItem('token');
        //清除用户名
        localStorage.removeItem('username');
        //跳转到登录页面
        window.location.href = '/login.html';
    })
}


// axios拦截器 请求拦截器 响应拦截器
axios.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers['Authorization'] = token;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
})

//响应拦截器

axios.interceptors.response.use(response => {
    //数据拆包 {data -->}

    return response.data
},function(error){
    //登录状态过期

    if (error.response.status === 401){
        localStorage.removeItem('username')
        localStorage.removeItem('token')
        showToast('登录状态过期，请重新登录')

        setTimeout(() => {
            location.href = '/login.html'
        }, 1500)
    }
    return Promise.reject(error)
})